package websocket;

import cn.hutool.json.JSONObject;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket
public class JSONHandler {

    @OnWebSocketConnect
    public void connected(Session session) {
        TalkWithServerHandler.userMap.put(session, "User" + TalkWithServerHandler.userId++);
    }

    @OnWebSocketClose
    public void closed(Session session, int statusCode, String reason) {
        TalkWithServerHandler.userMap.remove(session);
    }

    /**
     * 点对点用户之间通信
     * 通信格式：JSON
     * 参数：
     *      to：要与之通信的用户的ID
     *      content：要发送的信息
     *      例：{
     *              to:'2',
     *              content:'message'
     *          }
     *
     * @param session
     * @param message
     */
    @OnWebSocketMessage
    public void message(Session session, String message) {
        try {
            String userStr = TalkWithServerHandler.userMap.get(session);
            System.out.println("User: " + userStr);
            System.out.println("Message: " + message);

            JSONObject jsonObject = new JSONObject(message);
            String targetID = (String)jsonObject.get("to");
            String messageInfo = (String)jsonObject.get("content");

            // 获取要与之通信的用户ID
            String targetUser = "User" + targetID;
            if (!targetUser.equals("")) {
                for (Session session1 : TalkWithServerHandler.userMap.keySet()) {
                    if (TalkWithServerHandler.userMap.get(session1).equals(targetUser)) {
                        // 向要与之通信的用户发送消息
                        session1.getRemote().sendString("【" + userStr + "】发来信息：" + messageInfo);
                        break;
                    }
                }
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
